import sys
from PySide6.QtWidgets import (QApplication, QMainWindow,
                             QMenuBar, QMenu)
from PySide6.QtGui import QAction

class Demo(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('PyQt QMenu / sub-menu 示例')
        self.resize(400, 300)

        # ---------- 1. 拿到主窗口自带的菜单栏 ----------
        bar = self.menuBar()          # 返回 QMenuBar 对象（已存在，无需 new）

        # ---------- 2. 建一个顶级菜单 ----------
        file_menu = bar.addMenu('File(&F)')   # &F 给 Alt+F 快捷键

        # ---------- 3. 给 File 加普通条目 ----------
        new_action = QAction('New', self)
        new_action.triggered.connect(lambda: self.statusBar().showMessage('New clicked'))
        file_menu.addAction(new_action)

        file_menu.addSeparator()

        # ---------- 4. 在 File 里再加一个子菜单 ----------
        recent_menu = QMenu('Recent', self)   # 子菜单也是 QMenu
        file_menu.addMenu(recent_menu)        # 挂到父菜单

        # 往子菜单里塞几个 QAction
        for name in ('file1.txt', 'file2.txt', 'file3.txt'):
            act = QAction(name, self)
            act.triggered.connect(lambda _checked, n=name:
                                  self.statusBar().showMessage(f'Open {n}'))
            recent_menu.addAction(act)
            

        # ---------- 5. 再来一个 Quit ----------
        quit_action = QAction('Quit', self)
        quit_action.triggered.connect(QApplication.instance().quit)
        file_menu.addSeparator()
        file_menu.addAction(quit_action)

        # 状态栏
        self.statusBar().showMessage('Ready')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Demo()
    win.show()
    sys.exit(app.exec_())